﻿using System;
using fastCSharp.code.cSharp;
using System.Threading;

namespace diantou.web.exam
{
    /// <summary>
    /// 考试长连接轮询
    /// </summary>
    [fastCSharp.code.cSharp.webView(IsAjax = true, IsPool = true, IsPage = false)]
    partial class poll : web.poll<poll>
    {
        /// <summary>
        /// 查询信息
        /// </summary>
        private struct pollQuery
        {
            /// <summary>
            /// 考试会话标识
            /// </summary>
            public int SessionId;
        }
        /// <summary>
        /// 考试会话标识
        /// </summary>
        public int SessionId;
        /// <summary>
        /// 轮询回调处理
        /// </summary>
        private Action<fastCSharp.code.cSharp.asynchronousMethod.returnValue<int>> onMessageHandle;
        /// <summary>
        /// 轮询回调处理
        /// </summary>
        /// <param name="value"></param>
        private void onMessage(fastCSharp.code.cSharp.asynchronousMethod.returnValue<int> value)
        {
            Interlocked.Decrement(ref AsynchronousCount);
            if (value.Type == fastCSharp.code.cSharp.asynchronousMethod.returnType.Success && value.Value != 0)
            {
                SessionId = value.Value;
                callback();
            }
            else if (ifNoneMatch) notChanged304();
            else
            {
                fastCSharp.net.tcp.http.response response = cancelAsynchronous();
                response.SetETag(web.poll.nullETag);
                callback(ref response);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private bool loadView(pollQuery query)
        {
            int userId = web.pub.GetExamUserId(this);
            if (userId != 0)
            {
                if (onMessageHandle == null) onMessageHandle = onMessage;
                ifNoneMatch = requestHeader.IfNoneMatch.Count != 0;
                isVerify = true;
                setAsynchronous();
                Interlocked.Increment(ref AsynchronousCount);
                diantou.dataAccess.tcpCall.examUser.get(userId, query.SessionId, onMessageHandle);
            }
            return true;
        }
    }
}
